import axios from 'axios';
import { Message } from 'element-ui';
import { doEncrypt } from './api.js';

axios.defaults.timeout = 500000;
axios.defaults.baseURL ='';


//http request 拦截器
axios.interceptors.request.use(
  config => {
    const token=sessionStorage.getItem("token");
    // const token = getCookie('名称');注意使用的时候需要引入cookie方法，推荐js-cookie
    config.data = JSON.stringify(config.data);
    if(!config.headers.token){
       config.headers["token"]=token;
    }
   /* config.headers = {
      'Content-Type':'application/x-www-form-urlencoded'
    }*/
    /*
    config.headers = {
      'Content-Type':'application/json',
      'token':token
    }*/
    // if(token){
    //   config.params = {'token':token}
    // }
    return config;
  },
  error => {
    return Promise.reject(err);
  }
);


//http response 拦截器
axios.interceptors.response.use(
  response => {
    if(response.data.errCode ==2){
      router.push({
        path:"/login",
        query:{redirect:router.currentRoute.fullPath}//从哪个页面跳转
      })
    }
    return response;
  },
  error => {
    return Promise.reject(error)
  }
)
/**
 * 封装下载文件
 * @param {} url 
 * @param {*} options 
 */
export function exportExcel(appid,url, options = {}) {
  
  
  let ip="/"+appid+"/";

  let urls="";
  if(appid)
    urls=ip+url;
  else
    urls=url;
  urls=urls.replace("//","/");
  return new Promise((resolve, reject) => {
  
    axios.defaults.headers['content-type'] = 'application/json;charset=UTF-8'
    axios({
      method: 'post',
      url: urls, // 请求地址
      data: options, // 参数
      responseType: 'blob' // 表明返回服务器返回的数据类型
    }).then(
      response => {
        //console.log(response)
        resolve(response.data)
        let blob = new Blob([response.data], {
          type: 'application/vnd.ms-excel'
        })
        let fileName = Date.parse(new Date()) + '.xlsx'
        try{
          let content=response.headers;
          content=content["content-disposition"].replace("inline; filename = ","");
          content=content.replace("inline; filename =","");
          content=content.replace("attachment; filename=","");
          content=content.replace("attachment;filename=","");
          //console.log("content=="+content)
          if(content.indexOf("?")==-1){
           // console.log("content2=="+content)
            fileName=unescape(content)
          }
        }catch(e){}
       
        if (window.navigator.msSaveOrOpenBlob) {
          // console.log(2)
          navigator.msSaveBlob(blob, fileName)
        } else {
          // console.log(3)
          var link = document.createElement('a')
          link.href = window.URL.createObjectURL(blob)
          link.download = fileName
          link.click()
          //释放内存
          window.URL.revokeObjectURL(link.href)
        }
      },
      err => {
        reject(err)
      }
    )
  })
}
/**
 * 封装get方法
 * @param url
 * @param data
 * @returns {Promise}
 */

export function fetch2(url,params={}){
  let ip=localStorage.getItem("ip");
  return new Promise((resolve,reject) => {
    axios.get(ip+url,{
      params:params
    })
    .then(response => {
      resolve(response.data);
    })
    .catch(err => {
      reject(err)
    })
  })
}
export function fetch3(url,params={}){
 
  return new Promise((resolve,reject) => {
    axios.get(url,{
      params:params
    })
    .then(response => {
      resolve(response.data);
    })
    .catch(err => {
      reject(err)
    })
  })
}

/**
 * 封装post请求
 * @param url
 * @param data
 * @returns {Promise}
 */

 export function post(appid,url,data = {}){
   

  if(localStorage.getItem("isDev")=="Y"){
    
     if(appid=="business"){
       appid="business_ex"
     }
    if(appid=="bygex"){
        appid="bygex_ex"
    }
    if(appid=="cemetery"){
      appid="cemetery_ex"
  }
    url=url.replace("business/byg/print","business_ex/byg/print");
    
  }
  let ip="/"+appid+"/";

  let urls="";
  if(appid)
    urls=ip+url;
  else
    urls=url;
  
  if(urls.indexOf("http://")==-1)
    urls=urls.replace("//","/");

  let time2 = new Date().getTime(); //1603009495724,精确到毫秒
  data["time"]=""+time2;
  

  const token=sessionStorage.getItem("token");
  let sign="";
  let content="";
  for(let key in data){
    if(data[key]!=undefined)
      content=content+data[key];
  }
  
  content=content+token;
  sign=this.$md5(content); 
  let headers={
    'Content-Type':'application/json',
    'token':token,
    'sign':sign,
    'time':""+time2
  }
 
  return new Promise((resolve,reject) => {
    axios.post(urls,data,{
      headers:headers
    }).then(response => {
      try{
        if(response.data.errorToken=="token"){
          let isApp=localStorage.getItem("isApp");
          let isAppTop=localStorage.getItem("isAppTop");
          let sCode=localStorage.getItem("sCode");
          let filenames=localStorage.getItem("filenames");
          this.$router.push({'path':'/error_token'})
          localStorage.setItem("token","");
          sessionStorage.setItem("token","")
        }else
          resolve(response.data);
      }catch(e){
        resolve(response.data);

      }
     
    }).catch(err => {
      console.log(err.response)
      console.log(err,"err=======sss==="+url)
      try{
        if(err.response.data.message.indexOf("token")!=-1){
          let isApp=localStorage.getItem("isApp");
          let isAppTop=localStorage.getItem("isAppTop");
          let sCode=localStorage.getItem("sCode");
          let filenames=localStorage.getItem("filenames");
          this.$router.push({'path':'/error_token'})
          localStorage.setItem("token","");
          sessionStorage.setItem("token","")
          
          //this.$router.push({path:"/login?sCode="+sCode+"&isApp="+isApp+"&isAppTop="+isAppTop+"&filenames="+filenames});
          //window.location.href="/#/login?sCode="+sCode+"&isApp="+isApp+"&isAppTop="+isAppTop+"&filenames="+filenames
        }
      }catch(e){

      }
      try{
        if(err.response.data.message.indexOf("505:")!=-1){
          let isApp=localStorage.getItem("isApp");
          let isAppTop=localStorage.getItem("isAppTop");
          let sCode=localStorage.getItem("sCode");
          let filenames=localStorage.getItem("filenames");
          this.$router.push({'path':'/error_token?error='+err.response.data.message})
          localStorage.setItem("token","");
          sessionStorage.setItem("token","")
          
          //this.$router.push({path:"/login?sCode="+sCode+"&isApp="+isApp+"&isAppTop="+isAppTop+"&filenames="+filenames});
          //window.location.href="/#/login?sCode="+sCode+"&isApp="+isApp+"&isAppTop="+isAppTop+"&filenames="+filenames
        }
      }catch(e){}
      
      reject(err)
    })
  })
 }


 
/**
 * 封装post加密请求
 * @param url
 * @param data
 * @returns {Promise}
 */

 export function postEncrypt(appid,url,data = {}){
   

  if(localStorage.getItem("isDev")=="Y"){
    
      if(appid=="business"){
        appid="business_ex"
      }
      if(appid=="bygex"){
          appid="bygex_ex"
      }
      if(appid=="cemetery"){
        appid="cemetery_ex"
    }
    url=url.replace("business/byg/print","business_ex/byg/print");
    
  }
  let ip="/"+appid+"/";

  let urls="";
  if(appid)
    urls=ip+url;
  else
    urls=url;
  
  if(urls.indexOf("http://")==-1)
    urls=urls.replace("//","/");

  let time2 = new Date().getTime(); //1603009495724,精确到毫秒
  data["time"]=""+time2;
  

  const token=sessionStorage.getItem("token");
  let sign="";
  let content="";

  let datanew={};
  for(let key in data){
    if(data[key]!=undefined&&data[key]){
      content=content+data[key];
      datanew[key]=doEncrypt(data[key])

    }
      
  }
  
  content=content+token;
  sign=this.$md5(content); 
  let headers={
    'Content-Type':'application/json',
    'token':token,
    'sign':sign,
    'time':""+time2
  }
 
  return new Promise((resolve,reject) => {
    axios.post(urls,datanew,{
      headers:headers
    }).then(response => {
      resolve(response.data);
    }).catch(err => {
     
      try{
        if(err.response.data.message.indexOf("token")!=-1){
          let isApp=localStorage.getItem("isApp");
          let isAppTop=localStorage.getItem("isAppTop");
          let sCode=localStorage.getItem("sCode");
          let filenames=localStorage.getItem("filenames");
          this.$router.push({'path':'/error_token'})
          localStorage.setItem("token","");
          sessionStorage.setItem("token","")
          
          //this.$router.push({path:"/login?sCode="+sCode+"&isApp="+isApp+"&isAppTop="+isAppTop+"&filenames="+filenames});
          //window.location.href="/#/login?sCode="+sCode+"&isApp="+isApp+"&isAppTop="+isAppTop+"&filenames="+filenames
        }
      }catch(e){

      }
      try{
        if(err.response.data.message.indexOf("505:")!=-1){
          let isApp=localStorage.getItem("isApp");
          let isAppTop=localStorage.getItem("isAppTop");
          let sCode=localStorage.getItem("sCode");
          let filenames=localStorage.getItem("filenames");
          this.$router.push({'path':'/error_token?error='+err.response.data.message})
          localStorage.setItem("token","");
          sessionStorage.setItem("token","")
          
          //this.$router.push({path:"/login?sCode="+sCode+"&isApp="+isApp+"&isAppTop="+isAppTop+"&filenames="+filenames});
          //window.location.href="/#/login?sCode="+sCode+"&isApp="+isApp+"&isAppTop="+isAppTop+"&filenames="+filenames
        }
      }catch(e){}
      
      reject(err)
    })
  })
 }

 
 export async  function postAsync (appid,url,data = {}){
   

  if(localStorage.getItem("isDev")=="Y"){
    
     if(appid=="business"){
       appid="business_ex"
     }
    if(appid=="bygex"){
        appid="bygex_ex"
    }
    if(appid=="cemetery"){
      appid="cemetery_ex"
  }
    url=url.replace("business/byg/print","business_ex/byg/print");
    
  }
  let ip="/"+appid+"/";

  let urls="";
  if(appid)
    urls=ip+url;
  else
    urls=url;
  
  urls=urls.replace("//","/");

  let time2 = new Date().getTime(); //1603009495724,精确到毫秒
  data["time"]=""+time2;
  

  const token=sessionStorage.getItem("token");
  let sign="";
  let content="";
  for(let key in data){
    if(data[key]!=undefined)
      content=content+data[key];
  }

  content=content+token;
  sign=this.$md5(content); 
  var result=await axios.post(urls,data,{
    headers:{
      'Content-Type':'application/json',
      'token':token,
      'sign':sign,
      'time':""+time2
    }
  });
  new Promise ((resolve,reject) => {
    resolve(result.data);
  });
  
 }
 
 export async  function postAsync2 (appid,url,data = {}){
   

  if(localStorage.getItem("isDev")=="Y"){
    
     if(appid=="business"){
       appid="business_ex"
     }
    if(appid=="bygex"){
        appid="bygex_ex"
    }
    if(appid=="cemetery"){
      appid="cemetery_ex"
  }
    url=url.replace("business/byg/print","business_ex/byg/print");
    
  }
  let ip="/"+appid+"/";

  let urls="";
  if(appid)
    urls=ip+url;
  else
    urls=url;
  
  urls=urls.replace("//","/");

  let time2 = new Date().getTime(); //1603009495724,精确到毫秒
  data["time"]=""+time2;
  

  const token=sessionStorage.getItem("token");
  let sign="";
  let content="";
  for(let key in data){
    if(data[key]!=undefined)
      content=content+data[key];
  }

  content=content+token;
  sign=this.$md5(content); 
  var result=await axios.post(urls,data,{
    headers:{
      'Content-Type':'application/json',
      'token':token,
      'sign':sign,
      'time':""+time2
    }
  });
 return result.data;
  
 }
/**
 * 封装post请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function post2(url,data = {}){

  
  let time2 = new Date().getTime(); //1603009495724,精确到毫秒
  data["time"]=""+time2;
  

  const token=sessionStorage.getItem("token");
  let sign="";
  let content="";
  for(let key in data){
    if(data[key]!=undefined)
      content=content+data[key];
  }

  content=content+token;
  sign=this.$md5(content); 

 return new Promise((resolve,reject) => {
   axios.post(url,data,{
      headers:{
        'Content-Type':'application/json',
        'token':token,
        'sign':sign,
        'time':""+time2
      }
    }).then(response => {
          resolve(response.data);
        },err => {
          reject(err)
        })
 })
}

 /**
 * 封装patch请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function patch(url,data = {}){
  return new Promise((resolve,reject) => {
    axios.patch(url,data)
         .then(response => {
           resolve(response.data);
         },err => {
           reject(err)
         })
  })
}

 /**
 * 封装put请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function put(url,data = {}){
  return new Promise((resolve,reject) => {
    axios.put(url,data)
         .then(response => {
           resolve(response.data);
         },err => {
           reject(err)
         })
  })
}